import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const isAuthenticated = ref(false)
  const users = ref(JSON.parse(localStorage.getItem('users')) || [
    { username: '123456', password: '123456' }
  ])

// src/stores/auth.js
const register = (username, password) => {
  // 检查用户名是否存在
  if (users.value.some(u => u.username === username)) {
    return { success: false, message: '用户名已存在' }
  }
  
  // 创建新用户
  const newUser = { username, password }
  users.value.push(newUser)
  localStorage.setItem('users', JSON.stringify(users.value))
  
  return { 
    success: true, 
    user: newUser,
    message: '注册成功' 
  }
}

  const login = (username, password) => {
    const account = users.value.find(acc => 
      acc.username === username && acc.password === password
    )
    
    if (account) {
      user.value = { username }
      isAuthenticated.value = true
      return true
    }
    return false
  }

  const logout = () => {
    user.value = null
    isAuthenticated.value = false
  }

  return { 
    user, 
    isAuthenticated, 
    users: computed(() => users.value), // 暴露为只读
    register,
    login, 
    logout 
  }
})